package app.auto.runner.base;

import android.app.Activity;
import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.aliang.auto.R;

import app.auto.runner.base.utility.SlideBottomUtil;
import app.auto.runner.base.utility.xml.Parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

import app.auto.AndroidInstance;
import app.auto.runner.base.intf.FunCallback;

public class OneListView extends AndroidInstance {

    boolean defaultClose = false;
    private FunCallback itemclick;

    public OneListView setDefaultClose(boolean defaultClose) {
        this.defaultClose = defaultClose;
        return this;
    }

    String itemxml;
    int layoutid;
    List viewids;
    private FunCallback longClickfunCallback;
    private String emptystr = "";

    public OneListView setEmptystr(String emptystr) {
        this.emptystr = emptystr;
        return this;
    }

    public OneListView setViewids(List viewids) {
        this.viewids = viewids;
        return this;
    }

    public static void notifyAdapter(final ListView listview) {
        new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if (listview.getAdapter() instanceof BaseAdapter) {
                    ((BaseAdapter) listview.getAdapter()).notifyDataSetChanged();
                } else {
                    ((BaseAdapter) ((HeaderViewListAdapter) listview.getAdapter()).getWrappedAdapter()).notifyDataSetChanged();
                }
                listview.invalidate();
                return false;
            }
        }).sendEmptyMessage(0);
    }

    public OneListView setLayoutid(int layoutid) {
        this.layoutid = layoutid;
        return this;
    }

    ListView listview;
    BaseAdapter adapter;

    public ListView getListview() {
        return listview;
    }

    public View getview() {
        return (View) listview.getParent();
    }

    public BaseAdapter getAdapter() {
        return adapter;
    }

    List model;


    public OneListView setModel(List model) {
        this.model = model;
        return this;
    }

    public OneListView buildListView(List model, final FunCallback funCallback) {
        return setModel(model).buildListView(funCallback);
    }

    public OneListView setLongClick(FunCallback funCallback) {
        longClickfunCallback = funCallback;

        return this;
    }


    public OneListView setItemxml(String itemxml) {
        this.itemxml = itemxml;
        return this;
    }

    public boolean listsearchEditEnabled = true;

    public OneListView setListsearchEditEnabled(boolean listsearchEditEnabled) {
        this.listsearchEditEnabled = listsearchEditEnabled;
        return this;
    }

    View oneview;

    public OneListView buildListView(final FunCallback funCallback) {
        buildListViewPre(funCallback);

        setAdapter();

//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String string = parent.getItemAtPosition(position).toString();
//                if (funCallback != null) {
//                    funCallback.simpleRun(string);
//                    funCallback.onCallback(string, position);
////                    ((Dialog) funCallback.getParam()).dismiss();
////                    ((Dialog) funCallback.getParam()).cancel();
//                }
//            }
//        });

        return this;
    }

    public OneListView buildListViewPre(FunCallback funCallback) {
        itemclick = funCallback;

        oneview = LayoutInflater.from(getContext()).inflate(R.layout.onelistview_layout, null);
        ListView listView = oneview.findViewById(R.id.listview);
        this.listview = listView;
        return this;
    }

    public View getOneview() {
        return oneview;
    }

    public void setAdapter() {
        setAdapter(itemclick, oneview, this.listview);
    }

    private void setAdapter(FunCallback funCallback, View oneview, ListView listView) {
        if (listsearchEditEnabled) {
            oneview.findViewById(R.id.edit_layout).setVisibility(View.VISIBLE);
        } else {
            oneview.findViewById(R.id.edit_layout).setVisibility(View.GONE);
        }

//        listView.setPadding(30, 30, 30, 10);
        listView.setAdapter(adapter = new BaseAdapter() {
            Map<View, Integer> convertviews = new HashMap<View, Integer>();


            @Override
            public int getCount() {
                return model.size();
            }

            @Override
            public Object getItem(int position) {
                return model.get(position);
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, final ViewGroup parent) {
                List<View> cache = new ArrayList<View>();
                if (convertView == null) {
                    if (!TextUtils.isEmpty(itemxml)) {
                        convertView = Parser.withActivity((Activity) getContext()).parse(itemxml, null, null).getView();
                    } else if (layoutid != 0) {
                        convertView = LayoutInflater.from(getContext()).inflate(layoutid, null);
                    } else {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.auto_string_item_choosable, null);
                    }
                }
                convertviews.put(convertView, position);

                cache.clear();
                assignGroupChild(cache, (ViewGroup) convertView);
                String itv = "";
                if (getItem(position) instanceof Map) {
                    if (((Map) getItem(position)).size() == 1) {
                        itv = (String) ((Map) getItem(position)).values().iterator().next();

                    } else {
                        itv = (String) ((Map) getItem(position)).values().toString();

                    }
                } else if (getItem(position) instanceof List) {

                    int i = 0;
                    for (Object o : ((List) getItem(position))) {
                        if (i + 1 <= cache.size()) {
                            if (cache.get(i) instanceof TextView) {
                                ((TextView) cache.get(i)).setText(o.toString());
                            }
                        }
                        i++;
                    }
                } else {
                    itv = getItem(position).toString().replaceAll(emptystr, "");
                }
                if (TextUtils.isEmpty(itemxml)) {
                    if (layoutid == 0) {
                        ((TextView) convertView.findViewById(R.id.name)).setText(itv);

                    } else {
                        if (((TextView) convertView.findViewById(R.id.name)) != null) {
                            ((TextView) convertView.findViewById(R.id.name)).setText(itv);
                        } else
                            for (Object oid : viewids) {
                                int id = Integer.parseInt(oid.toString());
                                VDMapper.get(VDMapper.class, getContext()).setView(
                                        convertView.findViewById(id), itv.replaceAll(emptystr, ""));

                            }
                    }
                }

                convertView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {

                        String string = (String) model.get(convertviews.get(v));

                        if (longClickfunCallback != null) {
                            longClickfunCallback.simpleRun(string);
                            longClickfunCallback.onCallback(string, convertviews.get(v));

                        }
                        return false;
                    }
                });
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Object string = model.get(convertviews.get(v));

                        if (funCallback != null) {
                            funCallback.simpleRun(string);
                            funCallback.onCallback(string, convertviews.get(v));
                            if (defaultClose) {
                                if (funCallback.getParam() != null) {
                                    ((Dialog) funCallback.getParam()).dismiss();
                                    ((Dialog) funCallback.getParam()).cancel();
                                } else {
                                    ((SlideBottomUtil) funCallback.getParam()).dismiss();
                                }
                            }
//                    ((Dialog) funCallback.getParam()).dismiss();
//                    ((Dialog) funCallback.getParam()).cancel();
                        }
                    }
                });
                return convertView;
            }

            //if (v instanceof TextView) {
//                if (((List) getItem(position)).size() <= j + 1) {
//                    ToastUtil.live(getContext()).toast(((List) getItem(position)).get(j).toString());
//                    ((TextView) v).setText(((List) getItem(position)).get(j).toString());
//                }
//            }
            private void assignGroupChild(List<View> cache, ViewGroup vg) {

                for (int j = 0; j < vg.getChildCount(); j++) {
                    View v = vg.getChildAt(j);
                    if (v instanceof ViewGroup) {
                        assignGroupChild(cache, ((ViewGroup) v));
                    } else {
                        cache.add(v);
                    }
                }
            }
        });
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }
}
